<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType, ref, toRefs } from 'vue'
import useSchema from './hooks/useSchema'
import { AllSchemas, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { CurdData } from '@/api/supplierContact/types'
import { Dialog } from '@/components/Dialog'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { getSelectListApi } from '@/api/operator'
import { getListApi } from '@/api/supplierContact'
import { getFieldEnumApi } from '@/api/supplierContact'
import { FieldEnum } from '@/api/purchase/types'
import { getSelectEnumApi } from '@/api/warehouse'
import { SchemaConfig } from '@/api/global/types'
import { SelectEnum } from '@/api/warehouse/types'
import { getSupplierListApi } from '@/api/supplier'
import { useValidator } from '@/hooks/web/useValidator'
import useTagsInput from './hooks/useTagsInput'

defineOptions({
  name: 'BrandtSave'
})
const selectEnum = ref<SelectEnum>({})
const { t } = useI18n()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})
const supplierPreViewId = 'supplierPreView'
const supplierPreViewIdStore = preViewDialogStore(supplierPreViewId)

// 使用表单相关的 hooks
const { formRegister: tagsFormRegister, formMethods: tagsFormMethods } = useForm()
const {
  // setValues,
  getFormData: getTagsFormData,
  getElFormExpose: getTagsElFormExpose
  // setSchema
} = tagsFormMethods

// 使用标签输入相关的 hooks
const { tagsDialogVisible, tagsList, handleTagsButtonClick, removeTag } = useTagsInput()
const tagsObj = {
  tagsList,
  handleTagsButtonClick,
  removeTag
}

// 使用验证相关的 hooks
const { required } = useValidator()

// 定义标签对话框的表单模式
const schemaTagsDialog = reactive<FormSchema[]>([
  {
    field: 'tags',
    label: t('customer.tags'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  }
])

const formSubmit = async () => {
  const elFormExpose = await getTagsElFormExpose()
  elFormExpose?.validate(async (valid) => {
    if (valid) {
      const formData = await getTagsFormData()
      tagsList.push(formData.tags)
      tagsDialogVisible.value = false
    } else {
      console.log('submit fail')
    }
  })
}

const supplierList = ref([])

const getSupplierList = async () => {
  const res = await getSupplierListApi({})
  supplierList.value = res.data.list
}

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const uploadList = reactive<string[]>([]) // 图片列表

const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})

const getFieldList = async () => {
  const res = await getFieldEnumApi({ field: 'all' })
  fieldEnum.value = res.data
}

const getSelectEnumList = async () => {
  const res = await getSelectEnumApi()
  selectEnum.value = res.data
}

const fetchData = async () => {
  await getFieldList()
  await getSupplierList()
  await getSelectEnumList()

  const schemaConfig: SchemaConfig = {
    supplierList: supplierList,
    fieldEnum: fieldEnum,
    selectEnum: selectEnum,
    tagsObj: tagsObj
  }
  // 在获取完所有数据后， 继续执行您希望在获取完数据后执行的代码
  const { crudSchemas } = useSchema(schemaConfig)

  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)
  allSchemas.value = {
    formSchema: newSchemas.formSchema || []
  }
}
fetchData()

const rules: FormRules = reactive({})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    setValues({
      image: uploadList.join(',')
    })
    const formData = await getFormData()
    formData.tags = tagsList.join(',')

    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    await nextTick()
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Dialog
    v-model="supplierPreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="supplierPreViewIdStore.src" alt="Preview Image" />
  </Dialog>

  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />
  <Dialog width="30%" v-model="tagsDialogVisible" :title="t('customer.tags')">
    <Form
      ref="tagsForm"
      :schema="schemaTagsDialog"
      @register="tagsFormRegister"
      style="margin: 10px"
    />
    <template #footer>
      <BaseButton type="primary" @click="formSubmit">{{ t('dialogDemo.submit') }}</BaseButton>
      <BaseButton @click="tagsDialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
